<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购人" prop="purchaser">
        <el-input
          v-model="queryParams.purchaser"
          placeholder="请输入采购人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单批号" prop="batch">
        <el-input
          v-model="queryParams.batch"
          placeholder="请输入订单批号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购日期" prop="purTime">
        <el-input
          v-model="queryParams.purTime"
          placeholder="请输入采购日期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增订单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单id" align="center" prop="purId"/>
      <el-table-column label="总金额" align="center" prop="purPrice"/>
      <el-table-column label="采购人" align="center" prop="purchaser"/>
      <el-table-column label="订单批号" align="center" prop="batch"/>
      <el-table-column label="采购日期" align="center" prop="purTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleLookOrder(scope.row)"
          >查看
          </el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:order:edit']"-->
<!--          >修改-->
<!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购订单 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购人" prop="purchaser">
          <el-input v-model="user.userName" placeholder="请输入采购人" :disabled="true"/>
        </el-form-item>
        <el-button
          class="mb8"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="goodadd"
          v-hasPermi="['system:order:add']"
        >新增商品
        </el-button>

        <el-table
          :data="listMedicals"
          style="width: 100%">
          <el-table-column
            label="商品名称"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.medName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="进价"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.purPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.purGoodNum }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="合计"
            width="180">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.priceNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-row>
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑
                </el-button>
              </el-row>
              <el-row class="mt5">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete1(scope.$index, scope.row)">删除
                </el-button>
              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="订单批号" prop="batch" class="mt10">
          <el-input v-model="form.batch" placeholder="请输入订单批号"/>
        </el-form-item>

        <el-form-item label="采购日期" prop="purTime">
          <el-date-picker
            v-model="form.purTime"
            type="date"
            placeholder="请选择采购日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总金额" prop="purPrice">
            <el-input v-model="form.purPrice" readonly>
              <template slot="append">元</template>
            </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    2弹窗-->
    <el-dialog :title="title1" :visible.sync="open1" width="600px" append-to-body @closed="resetGood">
      <el-form ref="good" :rules="rules1" label-width="80px" :model="good">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="medName">
              <el-autocomplete
                popper-class="my-autocomplete"
                v-model="medName"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="handleSelect">
                <template slot-scope="{ item }">
                  <div>{{ item.medName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="器械类别" prop="medTypeId">
              <el-select v-model="medTypeId" placeholder="器械类别" @input="dataGood">
                <el-option label="一级" value="1"></el-option>
                <el-option label="二级" value="2"></el-option>
                <el-option label="三级" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="unit" placeholder="请输入内容" @input="dataGood"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零售价" prop="untitled">
              <el-input v-model="untitled" type="number" placeholder="请输入内容" @input="dataGood"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="展示图片" prop="medImage" @input="dataGood">
          <image-upload v-model="medImage"/>
        </el-form-item>
        <el-form-item label="产品介绍" prop="medInfo">
          <el-input v-model="medInfo" type="textarea" placeholder="请输入内容" @input="dataGood"/>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="进价" prop="purGoodPrice">
              <el-input v-model="purGoodPrice" type="number" placeholder="请输入内容" @input="totalPrice()"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="purGoodNum">
              <el-input v-model="purGoodNum" type="number" placeholder="请输入数量" @input="totalPrice()"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合计" prop="priceNum">
          <el-input v-model="priceNum" readonly>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>

    <!--    3弹窗-->
    <el-dialog :title="title2" :visible.sync="open2" width="600px" append-to-body @closed="resetGood">
      <el-form :rules="rules1" label-width="80px" :model="good">
        <el-row>
          <el-col :span="12">
            <el-form-item label="进价" prop="purGoodPrice">
              <el-input v-model="purGoodPrice" type="number" placeholder="请输入内容" @input="totalPrice()"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="purGoodNum">
              <el-input v-model="purGoodNum" type="number" placeholder="请输入数量" @input="totalPrice()"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合计" prop="priceNum">
          <el-input v-model="priceNum" readonly>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel3">取 消</el-button>
      </div>
    </el-dialog>

<!--    4弹窗-->
    <el-dialog :title="title2" :visible.sync="open4" width="800px" append-to-body @closed="reset">
      <el-row>
        <el-col :span="12">采购人：{{form.purchaser}}</el-col>
        <el-col :span="12">订单批号：{{form.batch}}</el-col>
      </el-row>
      <el-row class="mt10">
        <el-col :span="12">采购时间：{{form.purTime}}</el-col>
        <el-col :span="12">总金额：{{form.purPrice}}元</el-col>
      </el-row>

      <el-table
        class="mt10"
        :data="form.sysPurOrderGoodsList"
        style="width: 100%">
        <el-table-column
          label="商品名称"
          width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.medName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="进价"
          width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.purGoodPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="数量"
          width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.purGoodNum }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="合计"
          width="180">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.purGoodNum*scope.row.purGoodPrice }}元</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel2">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listOrder, getOrder, delOrder, addOrder, updateOrder} from "@/api/system/order";
import {getUserProfile} from "@/api/system/user";
import {listMedical} from "@/api/system/medical";
import {getMed} from "@/api/system/medical";

export default {
  name: "Order",
  data() {
    return {
      //绑定变量
      medId: "",
      medName: "",
      medTypeId: "",
      unit: "",
      untitled: "",
      medImage: "",
      medInfo: "",
      purGoodPrice: "",
      purGoodNum: "",
      priceNum: "",

      //表单定位
      index: '',
      //查询建议
      restaurants: [],
      state: '',
      timeout: null,
      //订单商品列表信息
      goodList: [],
      //单个商品信息
      good: {},
      // 用户信息
      user: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单 表格数据
      orderList: [],
      // 商品订单 数据
      listMedicals: [],
      // 弹出层标题
      title: "",
      title1: "",
      title2: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      open4:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaser: null,
        batch: null,
        purTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules:{
        batch: [
          {required: true, message: '请填写订单批号', trigger: 'blur'}
        ],
        purTime: [
          {required: true, message: '请选择日期', trigger: 'change'}
        ],
        purPrice: [
          {required: true, message: '请添加商品', trigger: 'blur'}
        ],
      },
      rules1: {
        medTypeId: [
          {required: true, message: '请选择商品类别', trigger: 'change'}
        ],
        unit: [
          {required: true, message: '请输入该单位', trigger: 'blur'}
        ],
        untitled: [
          {required: true, message: '请选择零售价', trigger: 'blur'}
        ],
        medImage: [
          {required: true, message: '请上传一张图片', trigger: 'change'}
        ],
        medInfo: [
          {required: true, message: '请输入商品介绍', trigger: 'blur'}
        ],
        purGoodPrice: [
          {required: true, message: '请填写进价', trigger: 'blur'}
        ],
        purGoodNum: [
          {required: true, message: '请填写数量', trigger: 'blur'}
        ],
        priceNum: [
          {required: true, trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getUser();
    this.getMedical();
  },
  methods: {

    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.medName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.medName = item.medName;
      this.medTypeId = item.medTypeId;
      this.medImage = item.medImage;
      this.unit = item.unit;
      this.untitled = item.untitled;
      this.medInfo = item.medInfo
      this.purGoodPrice = item.purGoodPrice
      this.priceNum = item.priceNum
      this.dataGood()
    },

    /** 计算商品单品总价*/
    totalPrice() {
      this.priceNum = (this.purGoodNum * this.purGoodPrice)
      this.dataGood()
    },
    /**计算订单总价 */
    totalOrderPrice() {
      if (this.listMedicals.length == 0){
        this.form.purPrice = null
      }else {
        this.listMedicals.forEach((item, index) => this.forPrice(item, index))
      }
    },
    forPrice(item,index) {
      if (index == 0) {
        this.form.purPrice = item.priceNum
      } else {
        this.form.purPrice = this.form.purPrice+item.priceNum
        console.log(this.form.purPrice)
      }
    },
    /** 查询商品列表*/
    getMedical() {
      listMedical().then(response => {
        this.restaurants = response.rows;
      });
    },

    /** 查询采购订单 列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户信息 */
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancel1() {
      this.open1 = false;
      this.reset()
    },
    cancel2() {
      this.open4 =false
      this.reset()
    },
    cancel3(){
      this.open2 =false
      this.resetGood()
    },


    // 表单重置
    reset() {
      this.form = {
        purId: null,
        purPrice: null,
        purchaser: null,
        batch: null,
        purTime: null,
      };
      this.listMedicals = []
      this.resetForm("form");
    },

    resetGood() {
      this.medId = ""
      this.medName = ""
      this.medTypeId = ""
      this.unit = ""
      this.untitled = ""
      this.medImage = ""
      this.medInfo = ""
      this.purGoodPrice = ""
      this.purGoodNum = ""
      this.priceNum = ""
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增订单商品操作 */
    goodadd() {
      this.open1 = true;
      this.title1 = "添加商品"
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purId = row.purId || this.ids
      getOrder(purId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单 ";
      });
    },

    /** 查看按钮 */
    handleLookOrder(row){
      const purId = row.purId || this.ids
      getOrder(purId).then(response => {
        this.form = response.data;
        this.open4 = true;
        this.title = "修改采购订单 ";
        console.log(response.data)
      });

    },

    /** 提交按钮 */
    submitForm() {
      this.form.purchaser = this.user.userName
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.list = this.listMedicals
            console.log(this.form)
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitForm1() {
      this.dataGood();
      this.$refs["good"].validate(valid => {
        if (valid) {
          getMed(this.good).then(response => {
            this.good.medId = response.data.medId
            this.$modal.msgSuccess("添加成功");
            this.getMedical();
            this.open1 = false;
            this.listMedicals.push(this.good)
            this.totalOrderPrice()
            this.resetGood()
          });
        } else {
          return false;
        }
      })
    },

    submitForm2() {
      this.listMedicals[this.index].priceNum = this.priceNum
      this.listMedicals[this.index].purGoodPrice = this.purGoodPrice
      this.listMedicals[this.index].purGoodNum = this.purGoodNum
      this.open2 = false
      this.totalOrderPrice()
      this.resetGood()
    },

    /** 数据绑定*/
    dataGood() {
      this.good = {
        medId: this.medId,
        medName: this.medName,
        medTypeId: this.medTypeId,
        unit: this.unit,
        untitled: this.untitled,
        medImage: this.medImage,
        medInfo: this.medInfo,
        purGoodPrice: this.purGoodPrice,
        purGoodNum: this.purGoodNum,
        priceNum: this.priceNum
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purIds = row.purId || this.ids;
      this.$modal.confirm('是否确认删除采购订单 编号为"' + purIds + '"的数据项？').then(function () {
        return delOrder(purIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    handleDelete1(index, row) {
      this.$delete(this.listMedicals, index)
      this.totalOrderPrice()
    },
    handleEdit(index, row) {
      this.open2 = true;
      this.index = index
      this.title2 = '编辑商品'
      this.medId = row.medId
      this.medName = row.medName
      this.medTypeId = row.medTypeId
      this.unit = row.unit
      this.untitled = row.untitled
      this.medImage = row.medImage
      this.medInfo = row.medInfo
      this.purGoodPrice = row.purGoodPrice
      this.purGoodNum = row.purGoodNum
      this.priceNum = row.priceNum
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
